<template>
  <div class="container mx-auto px-4 py-8">
    <h2 class="text-2xl font-bold mb-6">个人中心</h2>

    <div class="max-w-4xl mx-auto">
      <!-- 使用 flex 布局替代 el-row，更好的移动端适配 -->
      <div class="flex flex-col lg:flex-row gap-6">
        <!-- 左侧用户信息卡片 -->
        <div class="w-full lg:w-1/3">
          <el-card class="user-card sticky top-4">
            <div class="text-center">
              <el-avatar
                  :size="80"
                  :src="userStore.userInfo?.avatar"
                  class="mb-4"
              />
              <h3 class="text-xl font-bold mb-2">{{ userStore.userInfo?.nickname }}</h3>
              <p class="text-gray-500 mb-4">{{ userStore.userInfo?.email }}</p>
              <el-button type="primary" @click="showEditDialog = true">
                编辑资料
              </el-button>
            </div>
          </el-card>
        </div>

        <!-- 右侧信息展示 -->
        <div class="flex-1">
          <!-- 订单统计 -->
          <el-card class="mb-6">
            <template #header>
              <div class="flex justify-between items-center">
                <span class="font-bold">订单统计</span>
                <el-button text @click="router.push('/orders')">查看全部</el-button>
              </div>
            </template>
            <!-- 移动端优化的订单统计网格 -->
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
              <div class="text-center p-3 hover:bg-gray-50 rounded cursor-pointer"
                   @click="router.push('/orders?status=pending')">
                <p class="text-2xl font-bold text-primary mb-1">{{ stats.pending }}</p>
                <p class="text-gray-500 text-sm">待付款</p>
              </div>
              <div class="text-center p-3 hover:bg-gray-50 rounded cursor-pointer"
                   @click="router.push('/orders?status=processing')">
                <p class="text-2xl font-bold text-primary mb-1">{{ stats.processing }}</p>
                <p class="text-gray-500 text-sm">待发货</p>
              </div>
              <div class="text-center p-3 hover:bg-gray-50 rounded cursor-pointer"
                   @click="router.push('/orders?status=shipped')">
                <p class="text-2xl font-bold text-primary mb-1">{{ stats.shipped }}</p>
                <p class="text-gray-500 text-sm">待收货</p>
              </div>
              <div class="text-center p-3 hover:bg-gray-50 rounded cursor-pointer"
                   @click="router.push('/orders?status=completed')">
                <p class="text-2xl font-bold text-primary mb-1">{{ stats.completed }}</p>
                <p class="text-gray-500 text-sm">已完成</p>
              </div>
            </div>
          </el-card>

          <!-- 收货地址 -->
          <el-card class="mb-6">
            <template #header>
              <div class="flex justify-between items-center">
                <span class="font-bold">收货地址</span>
                <el-button text @click="router.push('/address')">管理地址</el-button>
              </div>
            </template>
            <div v-if="defaultAddress" class="p-4 border rounded hover:bg-gray-50">
              <div class="flex flex-col sm:flex-row sm:items-center justify-between">
                <div>
                  <p class="font-bold mb-1">
                    {{ defaultAddress.name }}
                    <span class="ml-4">{{ defaultAddress.phone }}</span>
                  </p>
                  <p class="text-gray-600" v-if="defaultAddress.region">{{ Array.isArray(JSON.parse(defaultAddress.region)) ? JSON.parse(defaultAddress.region).join('') : defaultAddress.region }}{{ defaultAddress.detail}}</p>
                </div>
                <div class="mt-2 sm:mt-0">
                  <el-tag type="success" size="small">默认地址</el-tag>
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无收货地址"/>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 编辑资料对话框 -->
    <el-dialog
        v-model="showEditDialog"
        title="编辑个人资料"
        width="90%"
        style="max-width: 600px"
        top="15vh"
    >
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="昵称">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称"/>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              action="/api/user/avatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
          >
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateProfile">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {useUserStore} from '@/stores/user'
import {Plus} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import router from "@/router/index.js";
import {getUserInfo, updateUserInfo} from "@/api/user.js";

const userStore = useUserStore()
const showEditDialog = ref(false)

// 模拟数据
const stats = ref({})

const defaultAddress = ref({})

const userForm = ref({
  nickname: userStore.userInfo?.nickname,
  avatar: userStore.userInfo?.avatar
})

const handleAvatarSuccess = (res) => {
  userForm.value.avatar = "http://localhost:8080" + res.data
}

const initData = async () => {
  const {data} = await getUserInfo()
  userStore.setUserInfo(data)
  stats.value = data.count
  defaultAddress.value = data.address
}
initData()
const handleUpdateProfile = async () => {
  try {
    await updateUserInfo(userForm.value)
    ElMessage.success('更新成功')
    showEditDialog.value = false
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

</script>

<style scoped>
.avatar-uploader {
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 移动端优化 */
@media (max-width: 640px) {
  .user-card {
    margin-bottom: 1rem;
  }

  .sticky {
    position: relative;
    top: 0;
  }
}

:deep(.el-drawer__body) {
  padding: 0;
  overflow: hidden;
}
</style>
